<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>1_引出生命周期</title>
  </head>
  <body>
    <div id="app"></div>
    <!-- 引入react核心库 -->
    <script src="../js/react.development.js"></script>
    <!-- 引入react-dom，用于支持react dom操作 -->
    <script src="../js/react-dom.development.js"></script>
    <!-- 引入babel，用于将jsx转为js -->
    <script src="../js/babel.min.js"></script>

    <script type="text/babel">
      // 创建组件
      class MyComponent extends React.Component {
        state = {
          opacity: 0.3
        }

        death = () => {
          // 卸载组件
          ReactDOM.unmountComponentAtNode(document.getElementById('app'))
        }

        componentDidMount() {
          // 组件挂载完毕
          console.log('组件挂载完毕')

          this.timer = setInterval(() => {
            // 获取原状态
            let { opacity } = this.state
            opacity -= 0.1
            if (opacity <= 0) opacity = 1
            this.setState({ opacity })
          }, 200)
        }

        componentWillUnmount() {
          // 组件即将卸载
          console.log('组件即将卸载')
          clearInterval(this.timer)
        }

        render() {
          return (
            <div>
              <h2 style={{ opacity: this.state.opacity }}>React学不会怎么办？</h2>
              <button onClick={this.death}>不活了</button>
            </div>
          )
        }
      }

      // 渲染组件到DOM
      ReactDOM.render(<MyComponent />, document.getElementById('app'))
    </script>
  </body>
</html>
